import json
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
# from reportlab.platypus import Image
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
# from reportlab.lib.utils import ImageReader
# import io
# import matplotlib.pyplot as plt
import os
# import matplotlib
# 设置matplotlib使用中文字体
# matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei']
# matplotlib.rcParams['axes.unicode_minus'] = False

class ReportGenerator:
    def __init__(self, json_data):
        self.data = json_data
        # 注册中文字体
        font_path = os.path.join(os.environ['WINDIR'], 'Fonts', 'msyh.ttc')
        pdfmetrics.registerFont(TTFont('MicrosoftYaHei', font_path))
        # 将普通字体也用作粗体
        pdfmetrics.registerFont(TTFont('MicrosoftYaHei-Bold', font_path))

    # def create_pie_chart(self):
    #     """创建饼图并返回图片数据"""
    #     # 过滤掉概率为0的数据
    #     labels = []
    #     probabilities = []
    #     for label, prob in zip(self.data['labels'], self.data['probabilites']):
    #         if prob > 0:
    #             labels.append(label)
    #             probabilities.append(prob)
    #
    #     # 创建图形
    #     plt.figure(figsize=(10, 8))
    #     plt.pie(probabilities, labels=labels, autopct='%1.1f%%')
    #     plt.title('故障概率分布')
    #
    #     # 将图片保存到内存中
    #     img_buffer = io.BytesIO()
    #     plt.savefig(img_buffer, format='png', bbox_inches='tight', dpi=300)
    #     img_buffer.seek(0)
    #     plt.close()
    #
    #     return img_buffer

    def generate_pdf(self, output_filename='report.pdf'):
        """生成PDF报告"""
        doc = SimpleDocTemplate(
            output_filename,
            pagesize=A4,
            rightMargin=72,
            leftMargin=72,
            topMargin=72,
            bottomMargin=72
        )

        # 创建样式
        styles = getSampleStyleSheet()
        title_style = ParagraphStyle(
            'CustomTitle',
            parent=styles['Heading1'],
            fontName='MicrosoftYaHei',
            fontSize=16,
            spaceAfter=30
        )
        normal_style = ParagraphStyle(
            'CustomBody',
            parent=styles['Normal'],
            fontName='MicrosoftYaHei',
            fontSize=10,
            leading=14
        )

        # 构建内容
        story = []

        # 添加标题
        story.append(Paragraph("故障诊断报告", title_style))
        story.append(Spacer(1, 20))

        # 创建故障概率表格
        table_data = [['故障类型', '概率 (%)']]
        for label, prob in zip(self.data['labels'], self.data['probabilites']):
            table_data.append([label, str(prob)])

        # 添加处理建议
        for i, issue in enumerate(self.data['issues'], 1):
            table_data.append([f'Treatment_{i:02d}', issue])

        table = Table(table_data, colWidths=[200, 200])
        table.setStyle(TableStyle([
            ('FONT', (0, 0), (-1, -1), 'MicrosoftYaHei'),
            ('FONTSIZE', (0, 0), (-1, -1), 10),
            ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ('FONT', (0, 0), (-1, 0), 'MicrosoftYaHei'),  # 修改这行，不使用Bold后缀
            ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
            ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
        ]))

        story.append(table)
        story.append(Spacer(1, 30))

        # # 创建并添加饼图
        # img_buffer = self.create_pie_chart()
        # img = ImageReader(img_buffer)
        #
        # # 获取图片尺寸并按比例缩放到合适大小
        # img_width, img_height = img.getSize()
        # aspect = img_height / float(img_width)
        #
        # # 设置图片在PDF中的宽度（根据需要调整）
        # desired_width = 400
        # desired_height = desired_width * aspect
        #
        # # 添加图片到PDF
        # story.append(Table([[Image(img_buffer, width=desired_width, height=desired_height)]],
        #                  colWidths=[desired_width]))
        # story.append(Spacer(1, 30))

        # 添加处理建议
        story.append(Paragraph("处理建议：", title_style))
        story.append(Spacer(1, 10))

        # 将处理建议文本按行分割并添加
        treatments = self.data['treatments'].split('\n')
        for treatment in treatments:
            if treatment.strip():
                story.append(Paragraph(treatment, normal_style))
                story.append(Spacer(1, 5))

        # 生成PDF
        doc.build(story)

# if __name__ == '__main__':
#     with open('D:\\pyspace\\audio-ai\\Outputs\\admin\\112\\MP3.json', 'r', encoding='utf-8') as f:
#         json_data = json.load(f)
#         generator = ReportGenerator(json_data)
#
#         output_filename = os.path.join('D:\\pyspace\\audio-ai\\Outputs\\admin\\112\\aa.pdf')
#         generator.generate_pdf(output_filename)
#         print(f"PDF报告已生成：{output_filename}")
#     import argparse
#     parser = argparse.ArgumentParser(description='生成故障诊断报告')
#     parser.add_argument('--json', type=str, help='JSON文件路径', default=None)
#     parser.add_argument('--output', type=str, help='输出PDF文件路径', default='fault_report.pdf')
#     args = parser.parse_args()
#
#     # 如果提供了JSON文件，则从文件读取数据
#     if args.json:
#         try:
#             with open(args.json, 'r', encoding='utf-8') as f:
#                 json_data = json.load(f)
#         except Exception as e:
#             print(f"读取JSON文件失败: {e}")
#             return
#     else:
#         # 使用默认数据
#         json_data = {
#             "labels": [
#                 "N_Belt_Friction",
#                 "N_Standing_Wave",
#                 "N_CSB_Echo",
#                 "N_MEF",
#                 "N_RG",
#                 "N_Rope",
#                 "N_Sheave",
#                 "N_Bearing"
#             ],
#             "probabilites": [0, 0, 54, 75, 5, 73, 5, 43],
#             "issues": ["MEF", "MEF"],
#             "treatments": "➣ MEF 噪音常见的结构原因包括:\n · 减振橡胶压溃或变形过大\n · 减振橡胶隔振效率低\n · Panel与主机共振引起噪音\n➣ MEF 噪音常见的电气原因包括:\n · 1x 编码器安装与屏蔽线及是否接地\n · 1x 主机绕线不良\n · 2x 供电电压不稳\n · 6x IGBT不良或载波\n · 主机气隙不良\n · 1x 2x 滤波参数\n · 霍尔传感器绕线与电流增益\n · 自学习参数如惯量或主机特性参数不准确\n"
#         }
#
#     try:
#         generator = ReportGenerator(json_data)
#         generator.generate_pdf(args.output)
#         print(f"PDF报告已生成：{args.output}")
#     except Exception as e:
#         print(f"生成PDF报告失败: {e}")
#
# if __name__ == "__main__":
#     # 故障诊断报告生成器.exe --json 数据.json --output 报告.pdf
#     main()